/**
 * Writed by yura and mak
 */

package wz.legend.util;

import org.apache.http.HttpEntity;
import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.util.EntityUtils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * User: yura
 */
public class RepeatingHttpEntity extends HttpEntityWrapper {
    byte[] buffer;

    public RepeatingHttpEntity(HttpEntity wrapped) {
        super(wrapped);
        if(wrapped instanceof BasicHttpEntity)
            try {
                ((BasicHttpEntity)wrapped).setContent(getContent());
            } catch (Exception e) {
                e.printStackTrace();
            } 
    }

    public InputStream getContent()
            throws IOException, IllegalStateException {

        if (buffer == null) {
            buffer = EntityUtils.toByteArray(wrappedEntity);
        }
        return new ByteArrayInputStream(buffer);
    }
}
